import sqlite3
from typing import Any, Dict, List

class GroupStore:
    def __init__(self, db="state.db") -> None:
        print(f"[DEBUG] 进入函数: GroupStore.__init__")
        self.conn = sqlite3.connect(db, check_same_thread=False)
        self.init()

    def init(self):
        print(f"[DEBUG] 进入函数: GroupStore.init")
        # 创建表，添加 type 字段来区分群组和频道
        self.conn.execute(
            'create table if not exists groups(id integer primary key, title text, baseline integer, type text default "群组")'
        )
        
        # 检查是否需要添加 type 列（兼容旧数据库）
        cursor = self.conn.execute("PRAGMA table_info(groups)")
        columns = [column[1] for column in cursor.fetchall()]
        if 'type' not in columns:
            print("[DEBUG] 添加 type 列到现有表")
            self.conn.execute('ALTER TABLE groups ADD COLUMN type text default "群组"')
        
        # 每次启动时清空所有群组/频道数据，重新获取最新信息
        print("[DEBUG] 清空数据库中的群组/频道数据")
        self.conn.execute('DELETE FROM groups')
        self.conn.commit()
        
        print("[DEBUG] 数据库已清空，准备重新获取群组/频道信息")
    
    def upsert_groups(self, rows) -> None:
        print(f"[DEBUG] 进入函数: GroupStore.upsert_groups")
        # 支持带类型信息的插入
        self.conn.executemany(
            'insert or replace into groups(id,title,baseline,type) values(?,?,?,?)',
            [(r['id'], r['title'], r['baseline'], r.get('type', '群组')) for r in rows]
        )
        self.conn.commit()

    def load_groups(self) -> List[Dict[str, Any]]:
        print(f"[DEBUG] 进入函数: GroupStore.load_groups")
        # 尝试读取包含类型信息的数据
        try:
            cur = self.conn.execute('select id, title, baseline, type from groups')
            return [{'id': r[0], 'title': r[1], 'baseline': r[2], 'type': r[3] or '群组'} for r in cur]
        except sqlite3.OperationalError:
            # 兼容旧数据库（没有 type 列）
            cur = self.conn.execute('select id, title, baseline from groups')
            return [{'id': r[0], 'title': r[1], 'baseline': r[2], 'type': '群组'} for r in cur]

    def update_baseline(self, gid, new_id) -> None:
        print(f"[DEBUG] 进入函数: GroupStore.update_baseline")
        self.conn.execute('update groups set baseline=? where id=?', (new_id, gid))
        self.conn.commit()
